package com.atguigu.spzx.manner.config;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.AuthContextUtil;
import com.atguigu.spzx.model.entity.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import spzx.util.AtguiguAssert;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求方式
        String method = request.getMethod();
        if("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true ;
        }
        String token = request.getHeader("token");
        AtguiguAssert.isTrue(!StringUtils.isEmpty(token), "token是空的");
        String json= (String) redisTemplate.opsForValue().get("user:login:"+token);
        AtguiguAssert.isTrue(!StringUtils.isEmpty(json), "用户不存在");
        SysUser sysUser = JSON.parseObject(json, SysUser.class);

        System.out.println("LoginAuthInterceptor preHandle");

        AuthContextUtil.set(sysUser);
        return true;
    }
}
